<template>
  <el-upload class="single-upload" ref="upload" accept="image/*" name="file" list-type="picture-card" :auto-upload="autoUpload"
             :on-exceed="handleExceed" :before-upload="beforeUpload" :action="host" :data="ossData" :on-success="handleSucsess"
             :on-error="handleErrors" :show-file-list="false">
    <i :class="[{'el-icon-plus':!uploading }, {'el-icon-loading': uploading}, 'upload-icon']"></i>
    <div class="single-up-img" v-if="imageUrl">
      <div class="opr-wrap">
        <p @click.stop>
          <i class="el-icon-delete" @click="handleRemoveImg"></i>
          <i class="el-icon-zoom-in" @click="handlePreview"></i>
        </p>
      </div>
      <img :src="imageUrl" class="avatar">
    </div>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </el-upload>
</template>

<script>
import { GetPictureUploadSignData } from '@/api/common'
export default {
  name: 'UploadImage',
  data () {
    return {
      uploading: false,
      host: '',
      ossData: {},
      autoUpload: true,
      imageUrl: '',
      vistUrl: '', // 图片上传后前置域名
      dialogVisible: false,
      dialogImageUrl: '',
      errorNum: 0 // 提示错误次数
    }
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    limitSize: {
      type: Object,
      default: () => {
        return {
          width: 0,
          height: 0
        }
      }
    },
    // 图片限制尺寸忽略范围
    limitSizeRange: {
      type: Number,
      default: 50
    }
  },
  created () { },
  mounted () {
    this.imageUrl = this.value
  },
  methods: {
    handleImgSize (file, callback) {
      return new Promise((resolve, reject) => {
        // 图片存储的大小单位为字节 kb mb
        let imgSize = file.size
        let limitSizeObj = this.limitSize
        const img = new Image()
        // 以字节多少比较
        const maxSize = this.memoryMaxSize * 1024 * 1024
        const imgSizeMb = (imgSize / 1024 / 1024).toFixed(2)
        if (imgSize > maxSize) {
          this.errorMsg(`上传图片大小为${imgSizeMb}M，超过${this.memoryMaxSize}M的限制，请重新上传...`)
        }

        img.onload = () => {
          const width = img.width
          const height = img.height

          if (limitSizeObj.width && width - limitSizeObj.width > 0) {
            this.errorMsg(`上传的图片尺寸宽为${width}，不符合图片的要求，请重新上传...`)
          } else if (limitSizeObj.height && height - limitSizeObj.height > 0) {
            this.errorMsg(`上传的图片尺寸高为${height}，不符合图片的要求，请重新上传...`)
          } else {
            // 正常 后续操作
            resolve(true)
            if (callback) callback(file)
          }
        }
        img.onerror = function () {
          this.$message.warning('图片尺寸不符合，请重新上传....')
        }
        img.src = window.URL.createObjectURL(file)
      })
    },

    beforeUpload (file) {
      // console.log(this.handleImgSize(file))
      return new Promise((resolve, reject) => {
        this.uploading = true
        GetPictureUploadSignData().then(res => {
          const data = res.data
          this.host = data.host
          let fileName = file.name
          let suffix = fileName.split('.')[1]
          const moment = new Date().getTime()
          fileName = `${moment}.${suffix}`
          this.ossData = {
            'key': `${data.dir}/${fileName}`,
            'policy': data.policy,
            'OSSAccessKeyId': data.accessKeyId,
            'signature': data.signature
          }
          // 图片上传后前置域名
          this.vistUrl = data.vistUrl
          resolve(true)
        }).catch(() => {
          this.uploading = false
          this.host = ''
          this.ossData = {}
          reject(new Error(false))
        })
      })
    },
    getSignData (file) {
      GetPictureUploadSignData().then(res => {
        const data = res.data
        this.host = data.host
        let fileName = file.name
        let suffix = fileName.split('.')[1]
        const moment = new Date().getTime()
        fileName = `${moment}.${suffix}`
        this.ossData = {
          'key': `${data.dir}/${fileName}`,
          'policy': data.policy,
          'OSSAccessKeyId': data.accessKeyId,
          'signature': data.signature
        }
        // 图片上传后前置域名
        this.vistUrl = data.vistUrl
      }).catch(() => {
        this.uploading = false
        this.host = ''
        this.ossData = {}
      })
    },
    handleGetSignData (file) {
      return new Promise((resolve, reject) => {
        this.uploading = true
        GetPictureUploadSignData().then(res => {
          const data = res.data
          this.host = data.host
          let fileName = file.name
          let suffix = fileName.split('.')[1]
          const moment = new Date().getTime()
          fileName = `${moment}.${suffix}`
          this.ossData = {
            'key': `${data.dir}/${fileName}`,
            'policy': data.policy,
            'OSSAccessKeyId': data.accessKeyId,
            'signature': data.signature
          }
          // 图片上传后前置域名
          this.vistUrl = data.vistUrl
          resolve(true)
        }).catch(() => {
          this.uploading = false
          this.host = ''
          this.ossData = {}
          reject(new Error(false))
        })
      })
    },
    errorMsg (message, type = 'warning', duration = 3) {
      if (this.errorNum <= 0) {
        this.$message({
          message: message,
          type: type,
          duration: duration * 1000
        })
      }
      this.errorNum++
    },
    handleSucsess (response, file, fileList) {
      const httpImgUrl = this.vistUrl + this.ossData.key
      this.imageUrl = httpImgUrl
      this.uploading = false
      this.upEmit()
    },

    handleErrors (errors, file, fileList) {
      this.upEmit()
    },

    handleRemoveImg () {
      this.imageUrl = ''
      this.upEmit()
    },

    handleExceed (value) {
      this.$message.warning(`上传图片不可超过${this.limit}张!`)
    },
    handlePreview () {
      this.dialogImageUrl = this.imageUrl
      this.dialogVisible = true
    },
    upEmit () {
      this.$emit('input', this.imageUrl)
    }

  }
}
</script>
